<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Models\Ranking;
use App\Models\Score;
use Exception;
use Illuminate\Support\Collection;
use Barryvdh\Debugbar\Facade as Debugbar;

class TestController extends Controller
{
    public function test(Request $request)
    {
        Debugbar::info(max(null, -1));
        return view('data');
    }

    public function test2(Request $request)
    {
        $id = 3;
        $solve = array(0, 5, 7, 2, 6, 3, 1, 4);
        $time = 99.3;
        $withAssist = false;

        $sequence = implode('', $solve);
        // with(['score', 'record', 'ranking'])->
        $user = User::find($id);
        $score = $user->score;
        $record = $user->record();

        if($withAssist) {
            $score->fastest_time_with_assist = $this->myMin($score->fastest_time_with_assist, $time);
        } else {
            $score->fastest_time_without_assist = $this->myMin($score->fastest_time_without_assist, $time);
        }

        $exist = $record->where('sequence', $sequence)->exists();
        // 新解法
        if(!$exist) {
            $ranking = $user->ranking;
            // null+1 == 1
            $ranking->solve_num += 1;
            $ranking->user_name = $user->name;
            // 要先save才能获取排名
            $ranking->save();

            $userRank = Ranking::getUserRank($id);
            $score->best_rank = $this->myMin($score->best_rank, $userRank);
            $score->solve_num += 1;
            $record->create([
                'sequence' => $sequence
            ]);

        }

        $score->save();

        return view('data');
    }


    public function myMin($value1, $value2)
    {
        return $value1==null ? $value2 : min($value1, $value2);
    }
}
?>
